package com.taiyuan.zfmvp.JUC.ThreadLocal;

import sun.security.ssl.HandshakeOutStream;

import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * @param
 * @Author: zhoufang@si-tech.com.cn
 * @Descriiption:
 * @Date 2022/10/23
 * @return
 */

class House{ //资源类

    int saleCount = 0;
    public synchronized  void saleHouse(){

        ++saleCount;

    }
    ThreadLocal<Integer> saleNum = ThreadLocal.withInitial(() -> 0);
    public void saleByLocal(){
        saleNum.set(1+saleNum.get());
    }
}

public class ThreadLocalDemo {



    //5个销售卖房子  集团高层只关心 销售总量的准确统计数
    public static void main(String[] args) {

        House house = new House();

        for (int i = 0; i < 5; i++) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    int size = new Random().nextInt(5)+1;
                    try {
                        for (int j = 1; j <= size ; j++) {
                            house.saleHouse();
                            house.saleByLocal();
                        }
                        System.out.println(Thread.currentThread().getName()+"号售卖出"+house.saleNum.get());
                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                        house.saleNum.remove();
                    }
                }
            },String.valueOf(i)).start();
        }
        try {
            TimeUnit.MILLISECONDS.sleep(300);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println(Thread.currentThread().getName()+"共卖出多少套:" + house.saleCount);

    }
}


